<template>
  <a-modal
    title="编辑歌曲"
    :width="600"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    okText="确认"
    cancelText="取消"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row :gutter="6">
          <a-col :md="12" :sm="24">
            <a-form-item
              label="歌名"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-input v-decorator="['songName', {initialValue: song.songName, rules: [{ required: true, message: '请输入歌名', trigger: 'blur' }]}]" />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="歌手"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-select
                mode="tags"
                placeholder="按回车分隔"
                v-decorator="['singerName', {initialValue: song.singerName.split('/'), rules: [{required: true, message: '请输入歌手'}]}]"
              >
                <a-select-option v-for="(item, index) in song.singerName.split('/')" :key="index" :value="item">
                  {{ item }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="专辑"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-input v-decorator="['albumName', {initialValue: song.albumName, rules: [{ required: true, message: '请输入专辑名', trigger: 'blur' }]}]" />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="简介"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-input v-decorator="['songInfo', {initialValue: song.songInfo}]" />
            </a-form-item>
          </a-col>
          <a-upload
            name="file"
            :file-list="fileList"
            :before-upload="beforeUpload"
            accept="audio/*"
            :remove="removeAudio"
          >
            <a-button> <a-icon type="upload" /> {{ fileList.length > 0 ? '更换音频' : '上传音频' }} </a-button>
          </a-upload>
          <a-col :md="20" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-checkbox :checked="isPublic" @change="changePublic">
                是否公开此歌曲（若无音频，不可公开）
              </a-checkbox>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { editSong } from '@/api/music/song'
import { upload, remove } from '@/api/file/file'
export default {
  name: 'EditSong',
  data () {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 21 }
      },
      confirmLoading: false,
      form: this.$form.createForm(this),
      visible: false,
      song: { singerName: '' },
      fileList: [],
      isPublic: false,
      isUpload: false,
      isRemove: false
    }
  },
  methods: {
    edit (record) {
      this.visible = true
      this.song = record
      this.isPublic = record.isPublic === 1
      if (record.audioUrl !== null) {
        this.fileList.push({
          uid: 0,
          name: record.audioName,
          status: 'done',
          url: 'http://127.0.0.1:9090/api/file/download/music/' + record.audioUrl
        })
      }
    },
    changePublic () {
      if (this.isPublic) {
        this.isPublic = false
      } else if (this.fileList.length > 0) {
        this.isPublic = true
      } else {
        this.$message.warning('请先选取音频文件！')
      }
    },
    removeAudio () {
      this.fileList = []
      this.isPublic = false
      this.isRemove = true
    },
    beforeUpload (file) {
      if (file.type.indexOf('audio') === -1) {
        this.$message.warning('请选择音频文件！')
        return
      }
      this.isUpload = true
      if (this.fileList.length > 0) {
        this.isRemove = true
      }
      this.fileList = [...[], file]
      return false
    },
    handleSubmit () {
      const { form: { validateFields } } = this
      this.confirmLoading = true
      validateFields((errors, values) => {
        if (!errors) {
          if (this.isUpload) {
            const formData = new FormData()
            formData.append('file', this.fileList[0])
            formData.append('type', 'music')
            upload(formData)
              .then(res => {
                if (res.data.message !== 'error') {
                  values.audioUrl = res.data.result.saveName
                  values.audioSize = res.data.result.size
                  values.audioName = this.fileList[0].name
                  this.submitSong(values)
                } else {
                  this.$message.error('音频文件上传失败！')
                }
              })
          } else {
            if (this.fileList.length > 0) {
              values.audioUrl = this.song.audioUrl
              values.audioName = this.song.audioName
            }
            this.submitSong(values)
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    submitSong (values) {
      values.songId = this.song.songId
      values.singerName = values.singerName.join('/')
      if (this.isPublic) {
        values.isPublic = 1
      } else {
        values.isPublic = 0
      }
      editSong(values)
        .then(res => {
          if (res.data.message !== 'error') {
            this.confirmLoading = false
            if (this.isRemove) {
              remove({ 'type': 'music', 'fileName': this.song.audioUrl })
                .then(res => {
                  if (res.data.message !== 'error') {
                    console.log(res.data.result)
                  } else {
                    console.log('服务器文件删除失败！----' + values.songName + ':' + this.song.audioName)
                  }
                })
            }
            this.reset()
            this.$emit('ok')
            this.$message.success('操作成功！')
          } else {
            this.$message.error('操作失败！')
          }
        })
    },
    handleCancel () {
      this.reset()
    },
    reset () {
      this.form.resetFields()
      this.visible = false
      this.song = { singerName: '' }
      this.fileList = []
      this.isPublic = false
      this.isUpload = false
      this.isRemove = false
    }
  }
}
</script>
